<template>
  <view class="layout layout-column">
    <van-sticky>
      <van-nav-bar
        :placeholder="true"
        title="点检"
        left-arrow
        @click-left="back"
      >
        <template #right>
          <van-button
            type="primary"
            @click="onSubmit"
            class="layout-btn"
            size="small"
            >提交</van-button
          >
        </template>
      </van-nav-bar>
    </van-sticky>
    <div class="van-list">
      <van-form>
        <van-field
          v-model="dataForm.checkUserName"
          name="checkUserName"
          label="点检人"
          required
          readonly
        />
        <van-field
          readonly
          clickable
          name="checkTime"
          required
          v-model="dataForm.checkTime"
          label="点检时间"
          @click="showPicker = true"
        />
        <van-field
          name="checkInstructions"
          rows="1"
          autosize
          type="textarea"
          v-model="dataForm.checkInstructions"
          label="点检说明"
        />
        <van-card v-for="item in list" :key="item.id">
          <template #title>
            <div class="title">
              点检项：{{ item.itemName
              }}{{ item.itemCode ? "【" + item.itemCode + "】" : "" }}
            </div>
          </template>
          <template #desc>
            <div class="item"><span>点检描述:</span> {{ item.itemRemark }}</div>
            <div class="item">
              <span>补充说明:</span> {{ item.supplementaryDescription }}
            </div>
            <div class="item">
              <span>点检结果:</span>
              <van-checkbox
                @change="onCheckbox($event, item)"
                :name="1"
                shape="square"
                v-model="item.itemResult"
                >通过</van-checkbox
              >
            </div>
            <van-uploader
              v-model="item.fileList"
              @delete="() => onDelete(item)"
              :after-read="(files, text) => afterRead(files, text, item)"
            />
          </template>
        </van-card>
      </van-form>
    </div>
    <van-popup v-model:show="showPicker" position="bottom">
      <van-datetime-picker
        @confirm="confirm"
        @cancel="showPicker = false"
        v-model="checkTime"
        type="datetime"
        title="点检时间"
        :min-date="minDate"
      />
    </van-popup>
  </view>
</template>
    
<script>
import { getCheckItem, check } from "@/api/home.js";
import { mapGetters, mapMutations } from "vuex";
import { Notify, Toast, Dialog } from "vant";
import dayjs from "dayjs";
export default {
  data() {
    return {
      loading: false,
      showPicker: false,
      value: "",
      dataForm: {
        checkTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
      },
      checkTime: new Date(),
      minDate: new Date(2024, 0, 1),
      list: [],
    };
  },
  computed: {
    ...mapGetters(["userInfo", "dataRow"]),
  },
  onLoad({ id }) {
    this.dataForm.checkBy = this.userInfo.userId;
    this.dataForm.checkUserName = this.userInfo.userName;
    this.getItemList(id);
  },
  mounted() {},
  methods: {
    async getItemList(id) {
      const res = await getCheckItem(id);
      if (res.data.length < 1) {
        return uni.showToast({
          icon: "none",
          title: "请维护点检项！",
          duration: 2000,
        });
      }
      this.list = res.data.map((item) => {
        item.itemResult = 1;
        item.fileList = [];
        return item;
      });
    },
    afterRead(file, { index }, row) {
      uni.uploadFile({
        url: "http://192.168.100.81:48801/api/dobo-file/files-anon", // 替换为你的上传接口
        name: "file",
        file: file.file,
        header: {
          "Dobo-Auth": "bearer " + uni.getStorageSync("token"),
          ContentType: "application/x-www-form-urlencoded",
        },
        success: (uploadFileRes) => {
          file.status = null;
          const result = JSON.parse(uploadFileRes.data);
          console.log("uploadFile success:", result.data);
          const { id, name, url } = result.data;
          row.fileList[index] = {
            ...row.fileList[index],
            name,
            url,
            fileId: id,
          };
          row.fileIds = row.fileList.map((item) => item.fileId);
        },
        fail: (error) => {
          console.error("uploadFile fail:", error);
          // 处理上传失败的结果
        },
      });
    },
    onDelete(row) {
      row.fileIds = row.fileList.map((item) => item.fileId);
    },
    back() {
      history.back();
    },
    onSubmit() {
      Dialog.confirm({
        title: "提示",
        message: !this.list.every((item) => item.itemResult == 1)
          ? "存在漏检项,是否继续提交？"
          : "是否确认提交？",
      }).then(async () => {
        const { id, equipName, equipCode } = this.dataRow;
        await check({
          ...this.dataForm,
          itemList: this.list,
          id,
          equipName,
          equipCode,
          result: this.list.every((item) => item.itemResult == 1) ? 1 : 0,
        });
        Toast.success("提交成功！");
        history.back();
      });
    },
    onClick(item) {
      //   uni.navigateTo({
      //     url: `/pages/detail/detail?id=${item.id}`,
      //   });
    },
    confirm(date) {
      this.dataForm.checkTime = dayjs(date).format("YYYY-MM-DD HH:mm:ss");
      this.showPicker = false;
    },
    onCheckbox(value, item) {
      item.itemResult = value ? 1 : 0;
    },
  },
};
</script>
    
    <style lang="scss" scoped>
.home {
  height: calc(100% - var(--van-tabbar-height));
  padding: 10px;
}
</style>
    